<template>
	<view class="message_content">
		<!-- 文字 -->
		<view v-if="item.Cmd === 1" class="text" v-html="item.Content.Text"></view>

		<!-- 图片 -->
		<view v-if="item.Cmd === 2">
			<up-image radius="5" :src="item.Content.Url" :width="`${item.Content.Width}upx`"
				:height="`${item.Content.Height}upx`" @tap="previewImage(item.Content.Url)">
				<template v-slot:error>
					<view class="errorImage"></view>
				</template>
				<template v-slot:loading>
					<view class="errorImage"></view>
				</template>
			</up-image>
		</view>

		<!-- 视频 -->
		<view v-if="item.Cmd === 3" @tap="playVideoFn(item)">
			<up-image radius="5" :src="item.Content.Url.replace('.mp4', '.jpg')" :width="`${item.Content.Width}upx`"
				:height="`${item.Content.Height}upx`">
				<template v-slot:error>
					<view class="errorVideo"></view>
				</template>
				<template v-slot:loading>
					<view class="errorVideo"></view>
				</template>
			</up-image>
			<view class="duration">{{ getVideoDuration(item.Content.Time) }}</view>
			<i class="videoPlayIcon"></i>
		</view>

		<!-- 语音 -->
		<view v-if="item.Cmd === 4" class="voiceProgress">
			<view @tap="playVoice(item.Content.Url)" :style="{ width: (item.Content.Time / 30) * 100 + '%' }"
				class="voiceFile" :class="{ playIcon: isPlaying }">
				{{ item.Content.Time }}"
			</view>
		</view>

		<!-- 文件 -->
		<view v-if="item.Cmd === 5" @tap="handleDownload(item.Content.Url)" class="operateFile">
			<view>
				<view>{{ item.Content.FileName }}</view>
				<view>{{ formatBytes(item.Content.Size) }}</view>
			</view>
			<view>
				<image :src="getImageSrc(item.Content.FileName)" mode="widthFix" />
			</view>
		</view>

		<!-- 红包 -->
		<view v-if="item.Cmd === 6" class="redCom">
			<view class="red" :class="{ disabled: item.Content.stateType }" @tap="receiveRedEnvelopeFn(item)">
				<view>
					<view>{{ item.Content.remarks }}</view>
					<view v-if="item.Content.tips">{{ item.Content.tips }}</view>
				</view>
				<view>IM红包</view>
			</view>
		</view>

		<!-- 通话消息 -->
		<view v-if="item.Cmd === 7" class="text">
			<view :class="'callIcon' + item.Content.call_type" @tap="handleCallFn(item.Content.call_type)">
				{{item.Content.text==-1?'通话忙线中':
          (item.Content.call_type == 1 ? "语音" : "视频") +
          (item.Content.callDuration ? `通话时长 ${item.Content.text}` : "通话已取消")
        }}
			</view>
		</view>
		<view v-if="item.Cmd === 8" class="text">
			<view :class="'callIcon' + item.Content.call_type" @tap="handleCallFn(item.Content.call_type)">
				{{ item.Content.call_type == 1 ? "语音" : "视频" }}通话未接听
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, onUnmounted, onBeforeUnmount } from "vue";
	import { onHide } from "@dcloudio/uni-app";
	import {
		getVideoDuration,
		getImageSrc,
		formatBytes,
		handleDownload,
	} from "@/static/ts/common";
	const emit = defineEmits();

	const props = defineProps({
		item: {
			type: Object as () => any,
			default: () => ({ Cmd: 1, Content: { Text: "" } }),
		},
		messagesList: {
			type: Array as () => any[],
			default: () => [],
		},
		messageType: {
			type: Number,
			default: 1,
		},
		index: {
			type: Number,
			default: null,
		},
	});
	let innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;

	// 播放视频
	const isPlaying = ref(false);
	const playVideoFn = (item : any) => {
		emit("playVideoFn", item);
	};

	// 打开红包
	const receiveRedEnvelopeFn = (item : any) => {
		emit("receiveRedEnvelopeFn", item);
	};
	// 重新拨打电话
	const handleCallFn = (call_type : number) => {
		emit("handleCallFn", call_type);
	};

	// 预览图片或视频
	const previewImage = (contentUrl : string) => {
		let urls = props.messagesList
			.filter((item) => item.Cmd === 2)
			.map((item) => item.Content.Url || "");

		// 倒序数组
		urls.reverse();

		let current = urls.findIndex((url) => url === contentUrl);

		if (props.messageType === 2) {
			current = 0;
			urls = [contentUrl];
		}

		uni.previewImage({
			current,
			urls,
		});
	};
	// 播放语音
	const playVoice = (voicePath : string) => {
		uni.showLoading({ mask: true });

		// 如果路径发生变化，重新加载并播放音频
		if (innerAudioContext.src !== voicePath) {
			innerAudioContext.src = voicePath;
			console.log("加载并播放");

			// 监听音频加载完成
			innerAudioContext.onCanplay(() => {
				console.log("音频已加载，开始播放");
				isPlaying.value = true;
				innerAudioContext.play();
				uni.hideLoading();
			});

			// 如果音频加载失败，显示错误并隐藏加载提示
			innerAudioContext.onError((error) => {
				isPlaying.value = false;
				console.error("音频加载失败", error);
				uni.hideLoading();
			});

			// 监听播放完成
			innerAudioContext.onEnded(() => {
				console.log("音频播放完毕");
				uni.hideLoading();
				isPlaying.value = false;
			});
		} else {
			// 如果音频正在播放，暂停；如果暂停了，就继续播放
			if (innerAudioContext.paused) {
				console.log("继续播放");
				isPlaying.value = true;
				innerAudioContext.play();
				uni.hideLoading();
			} else {
				pauseVoice();
			}
		}
	};

	// 暂停语音
	const pauseVoice = () => {
		isPlaying.value = false;
		innerAudioContext?.pause();
	};

	// 在需要监听的组件或页面中
	uni.$on("myCustomEvent", (data) => {
		pauseVoice();
	});

	onUnmounted(() => {
		pauseVoice();
	});

	onHide(() => {
		pauseVoice();
	});

	defineExpose({
		pauseVoice,
	});
</script>

<style scoped lang="scss">
	@import "../../../static/scss/chat.scss";
</style>